const execa = require("execa");
const semver = require("semver");
const inquirer = require("inquirer");
const { format } = require("./utils");
const currentVersion = require("./package.json").version;
// test
const execaWithLog = async (file, args, options) => {
  const { stdout } = await execa(file, args, options);
  console.log(stdout);
};

const publish = async () => {
  console.log("publish start");
  // await execaWithLog("git", ["pull"]);
  console.log(`Current version: ${currentVersion}`);

  const bumps = ["patch", "minor", "major"];
  const versions = {};
  bumps.forEach(b => {
    versions[b] = semver.inc(currentVersion, b);
  });
  const bumpChoices = bumps.map(b => ({
    name: `${b} (${versions[b]})`,
    value: b
  }));

  const { bump, customVersion } = await inquirer.prompt([
    {
      name: "bump",
      message: "Select release type:",
      type: "list",
      choices: [...bumpChoices, { name: "custom", value: "custom" }]
    },
    {
      name: "customVersion",
      message: "Input version:",
      type: "input",
      when: answers => answers.bump === "custom"
    }
  ]);

  const version = customVersion || versions[bump];

  const { isConfirm } = await inquirer.prompt([
    {
      name: "isConfirm",
      message: `Confirm releasing ${version}?`,
      type: "confirm"
    }
  ]);

  if (isConfirm) {
    await execaWithLog("git", ["add", "-A"]);
    await execaWithLog("git", [
      "commit",
      "-m",
      `build: build production v${version} at ${format()}`
    ]);
    await execaWithLog("npm", [
      "version",
      version,
      "-m",
      `chore: update version with tag v${version}`
    ]);
    await execaWithLog("git", ["push", "origin", `v${version}`]);
    await execaWithLog("git", ["push", "origin", "master"]);
  }
  console.log("publish end");
};

publish().catch(err => {
  console.error(err.stderr);
  console.error(err.stdout);
  process.exit(1);
});
